/**
 * 142. 环形链表 II
 * https://leetcode-cn.com/problems/linked-list-cycle-ii/
 */
const { createListNode } = require('../../libs/public');

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
function detectCycle(head) {
  let slow = head;
  let fast = head;
  while (fast) {
    slow = slow.next;
    if (fast.next) {
      fast = fast.next.next;
    } else {
      return null;
    }
    if (slow === fast) {
      slow = head;
      while (slow !== fast) {
        slow = slow.next;
        fast = fast.next;
      }
      return slow;
    }
  }
  return null;
}

console.log(detectCycle(createListNode([3, 2, 0, -4], 1)).val === 2);
console.log(detectCycle(createListNode([1, 2], 0)).val === 1);
console.log(detectCycle(createListNode([1])) === null);
console.log(detectCycle(createListNode([1], 0)).val === 1);
console.log(detectCycle(createListNode([])) === null);
